#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <Arduino.h>
#include <IRremoteESP8266.h>
#include <IRrecv.h>
#include <IRutils.h>
#include "oled.h"
#include "display.h"

int RECV_PIN = 1;//红外接口
IRrecv irrecv(RECV_PIN);
decode_results results;


unsigned int read_port = 666;  //监听端口666
WiFiUDP udp;                    //定义udp
const int NTP_PACKET_SIZE = 52;
static char packerBuffer[NTP_PACKET_SIZE];//接收数据缓冲
String data_ = "";  //接收数据
String stata_ = "";
 //出可视化模式不进入WIFI红外模式

long ir_value();                  //接收红外数据数据
void ir_handler(long data);       //处理红外数据
void sendNTPpacket(String data);  //处理udp数据,并反馈客户端
String Readpacket();              //接收udp数据 
int Wifi_wait;//等待入网时间        
void setup() {
  pinMode(OLED_SCL  , OUTPUT);
  pinMode(OLED_SDIN , OUTPUT);
  pinMode(key1, INPUT_PULLUP);
  pinMode(key2, INPUT_PULLUP);
  pinMode(key3, INPUT_PULLUP);
  pinMode(Key_Exit, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
 // digitalWrite(Key_Exit,0);
  Wifi_wait = 10;   
  Serial.begin(9600);
  Serial.println("开始：");//串口输出打开

   OLED_Init();
   OLED_Clear();
   OLED_DrawBMP(0 , 0 , 128, 8,BMP1);
   for(int i=0; i<10; i++)
     OLED_ShowChar(32+i*8, 6, 10+i);
   OLED_ShowChar(113, 6, Wifi_wait/10);
   OLED_ShowChar(121, 6, Wifi_wait%10);
   OLED_ShowCHinese(111, 0,88);
   
  WiFi.mode(WIFI_STA);
  /* start SmartConfig */
  WiFi.beginSmartConfig();
  /* Wait for SmartConfig packet from mobile */
  Serial.println("Waiting for SmartConfig.");
  int i=0;
  while (!WiFi.smartConfigDone() && Wifi_wait > 0) {  //接收自动配网数据包或者40s以后跳过，接收配网数据包时指示灯闪烁
    delay(1000);
    Wifi_wait--;
   OLED_ShowChar(113, 6, Wifi_wait/10);
   OLED_ShowChar(121, 6, Wifi_wait%10);
    Serial.print(".");
    i++;
  }
  /* Wait for WiFi to connect to AP */
  i=0;
  if(WiFi.smartConfigDone()){      //接收到配网数据包后连接wifi
    Serial.println("");
    Serial.println("SmartConfig done.");
    Serial.println("Waiting for WiFi");
  while ((WiFi.status() != WL_CONNECTED) && i<40) {  //连接wifi
    delay(300);
    Serial.print(".");
    i++;
  }
}    
  if(WiFi.status() == WL_CONNECTED){   //连上网串口输出信息，打开upd
  Serial.println("WiFi Connected.");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());
  udp.begin(read_port);
}else{
   Serial.println("WiFi NO!!Connected..."); 
}
  irrecv.enableIRIn();

  Mode_Display();

}



void loop() {
/*-----------------oled可视化------------------*/
       /*-----------模式选择------------*/
if(!digitalRead(key1) || !digitalRead(key2)){//选择
      delay(50);
    if(!digitalRead(key1) || !digitalRead(key2)){
      for(int cl=0; cl<4; cl++)  //清指针
       OLED_ShowCHinese(0, cl*2, 0);
     if(!digitalRead(key1)){
       Mode_i++;
     if(Mode_i==4) Mode_i=0; 
       }
     if(!digitalRead(key2)){
       Mode_i--;
       if(Mode_i==-1) Mode_i=3;
    }
    OLED_ShowCHinese(0, Mode_i*2, 1); 
   }
 }
      /*---------进入模式-----------*/ 
if(!digitalRead(key3)){
  delay(50);
  if(!digitalRead(key3)){
     OLED_Clear();//清屏
    if(Mode_i==0){
         Mode_One();
    }
    else if(Mode_i==1){
         Mode_two();
    }
    else if(Mode_i==2){
         Mode_three();
    }
    else if(Mode_i==3){
         Mode_four();
    }
    else{    
    }
  } 
 }//进入可视化模式

 if(WiFi.status() != WL_CONNECTED){
      //Serial.println("断网..."); 
      OLED_ShowCHinese(111, 0,88);//断网logo
   }
   else{  
    OLED_ShowCHinese(111, 0,87);//入网logo
     if((data_ = Readpacket())!="0" ){
          sendNTPpacket(data_);
     }  
  }               
       ir_handler(ir_value() );

       flag_wifi = 1;
   }//结束主函数

/**************************************/
/*************接收红外数据**************/
long ir_value()
{
  long data = 0;     Serial.print("进入红外接收");
  if(irrecv.decode(&results)){
 //    Serial.println();
     data = results.value;
     irrecv.resume();

     Serial.println(data);
     return data;
  }
}
/*********************************/
/***********处理红外数据************/
void ir_handler(long data){
  if(data || flag_wifi){
   Serial.println(data);           //打印10进制红外编码
if (data == 16724175){               //一号编码
    digitalWrite(LED,!digitalRead(LED));
  }
 }
} 
/******************接收upd数据******************/
 String Readpacket(){ 
   int cb = udp.parsePacket();
    if(!cb || !flag_wifi){
      return "0";               //没有数据返回"0";
      }
      else{
           udp.read(packerBuffer, NTP_PACKET_SIZE);
      
           Serial.print("接收客户端数据包:");
           packerBuffer[cb] = 0;    //写0转化成字符串
           Serial.printf("%s  ", packerBuffer);
           Serial.printf("接收数据大小:%d字节 来自服务器IP:%s, 端口:%d\n", cb, udp.remoteIP().toString().c_str(),udp.remotePort());//服务器信息 
           return packerBuffer;
        } 
    }
/************处理数据并返回****************/
  void sendNTPpacket(String data){
   memset(packerBuffer,0,NTP_PACKET_SIZE);//回传数据缓冲
      if(digitalRead(LED))
        stata_ = "1号打开,";
   memset(packerBuffer,0,stata_.length());
     for(int i=0; i<stata_.length(); i++)
     {
        packerBuffer[i] = stata_[i];        //如何把String类型付给char数组，strcpy不行
     }
  
 /**************打开*****************/       
    if(data =="open")
           {
             digitalWrite(LED, 1);
             strcpy(packerBuffer,"oneisopen");
           }       
 /******************关闭************************/
      else if(data =="close")
           {
             digitalWrite(LED, 0);
             strcpy(packerBuffer,"oneisclose");
           }       
   /*************向客户段返回数据***************/     
    udp.beginPacket(udp.remoteIP(),udp.remotePort());
    udp.write(packerBuffer, NTP_PACKET_SIZE);
    udp.endPacket();
          strcpy(packerBuffer,"       ");//覆盖发送缓存
 }
/**************************************************/
/**************************************************/

  
